package com.pucong.gitee.database.backup.configuration.authorize;

import com.pucong.gitee.database.backup.common.entity.sys.authorize.AuthorizeInfo;
import com.pucong.gitee.database.backup.common.selfenum.LicenceTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

@Slf4j
public final class LicenseManager {

    private AuthorizeInfo productLicense;

    private String licPath;

    LicenseManager(String licPath){
        this.licPath = licPath;
    }

    public AuthorizeInfo getLicense() {
        if (productLicense == null) {
            SAXReader saxreader = new SAXReader();
            try {
                Document document = saxreader.read(new File(licPath));
                productLicense = fromXML(document);
            } catch (Exception e) {
               return null;
            }
        }
        return productLicense;
    }

    public AuthorizeInfo fromXML(Document paramDocument) throws ParseException {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        AuthorizeInfo localLicense = new AuthorizeInfo();
        Element localElement1 = paramDocument.getRootElement();
        localLicense.setLicType(LicenceTypeEnum.临时);
        String str2 = localElement1.elementText("expire-date").replace("\u200e","");
        localLicense.setExpireDate(dateFormat.parse(str2));
        localLicense.setMac(localElement1.elementText("mac").replace("\u200e",""));
        String signature = localElement1.elementText("signature").replace("\u200e","");
        localLicense.setServerKey(signature);

        byte[] signByte = null;
        try {
            signByte = localElement1.elementText("signature").getBytes("UTF-8");
        } catch (Exception e) {
            log.error("获取密钥失败",e);
        }
        localLicense.setSignature(signByte);
        return localLicense;
    }
}